from datetime import datetime
from app import db

class Banner(db.Model):
    """Banner模型"""
    __tablename__ = 'banners'
    
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False, comment='标题')
    description = db.Column(db.Text, comment='描述')
    image_url = db.Column(db.String(500), nullable=False, comment='图片URL')
    link_url = db.Column(db.String(500), comment='跳转链接')
    link_type = db.Column(db.String(20), default='external', comment='链接类型：external-外部链接，internal-内部页面，venue-场馆详情，miniprogram-小程序跳转，none-纯展示无跳转')
    link_target = db.Column(db.String(50), comment='链接目标：venue_id或页面路径或小程序页面路径')
    link_appid = db.Column(db.String(50), comment='小程序AppID（link_type为miniprogram时使用）')
    sort_order = db.Column(db.Integer, default=0, comment='排序序号，数字越小越靠前')
    status = db.Column(db.SmallInteger, default=1, comment='状态：0-禁用，1-启用')
    start_time = db.Column(db.DateTime, comment='开始展示时间')
    end_time = db.Column(db.DateTime, comment='结束展示时间')
    click_count = db.Column(db.Integer, default=0, comment='点击次数')
    created_by = db.Column(db.Integer, db.ForeignKey('admins.id'), comment='创建人')
    created_at = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    
    # 关系
    creator = db.relationship('Admin', backref='banners')
    
    def to_dict(self, include_stats=False):
        """转换为字典"""
        data = {
            'id': self.id,
            'title': self.title,
            'description': self.description,
            'image_url': self.image_url,
            'link_url': self.link_url,
            'link_type': self.link_type,
            'link_target': self.link_target,
            'link_appid': self.link_appid,
            'sort_order': self.sort_order,
            'status': self.status,
            'start_time': self.start_time.isoformat() if self.start_time else None,
            'end_time': self.end_time.isoformat() if self.end_time else None,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
        
        if include_stats:
            data['click_count'] = self.click_count
            data['creator_name'] = self.creator.name if self.creator else None
            
        return data
    
    @staticmethod
    def get_active_banners():
        """获取有效的banner列表"""
        from datetime import datetime
        now = datetime.utcnow()
        
        return Banner.query.filter(
            Banner.status == 1,
            db.or_(Banner.start_time.is_(None), Banner.start_time <= now),
            db.or_(Banner.end_time.is_(None), Banner.end_time >= now)
        ).order_by(Banner.sort_order.asc(), Banner.created_at.desc()).all()
    
    def is_active(self):
        """检查banner是否有效"""
        if self.status == 0:
            return False
            
        now = datetime.utcnow()
        if self.start_time and self.start_time > now:
            return False
            
        if self.end_time and self.end_time < now:
            return False
            
        return True
    
    def increment_click(self):
        """增加点击次数"""
        try:
            self.click_count += 1
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            from flask import current_app
            current_app.logger.error(f"增加Banner点击次数失败: {str(e)}")
            raise e
        
    def __repr__(self):
        return f'<Banner {self.title}>' 